<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Models\Role;
use App\Models\User;


class UsersController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        // 中间件 -- 超级管理员不允许修改角色.删除
        $this->middleware(function ($request, $next) {
            // 获取当前访问方法
            $action = request()->route()->getActionMethod();
            if (in_array($action, ['destroy', 'editrole', 'updaterole'])) {
                if ($request->user == 1) {
                    session()->flash('danger', '超级管理员不允许操作');
                    return back();
                }
            }
            return $next($request);
        });
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $users = User::query();
        $key = $request->input('key', '');
        // 判断是否有搜索值
        if ($request->filled('key')) {
            // 查询相关数据
            $users = $users->where('name', 'like', '%' . $key . '%')
                ->orWhere('email', 'like', '%' . $key . '%');
        }
        $users = $users->paginate(10);
        return view('admin.users.index', compact('users', 'key'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.users.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:users|max:50',
            'email' => 'required|email|unique:users|max:255',
            'password' => 'required|confirmed|min:6',
        ]);

        $user = new User;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);

        if ($user->save()) {
            session()->flash('success', '保存成功');
            return redirect()->route('users.index');
        } else {
            session()->flash('danger', '保存失败');
            return redirect()->back();
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::find($id);
        return view('admin.users.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $this->validate($request, [
            'name' => 'nullable|unique:users|max:50',
            'oldpassword' => 'nullable|min:6',
            'password' => 'nullable|confirmed|min:6',
        ]);

        $user = User::find($id);
        $request->filled('name') && $user->name = $request->name;
        // 判断是否修改密码
        if ($request->filled('oldpassword') && $request->filled('password')) {
            // 验证原密码是否正确
            if (\Hash::check($request->oldpassword, $user->password)) {
                $user->password = bcrypt($request->password);
            } else {
                session()->flash('danger', '原密码不正确,请输入正确的密码');
                return redirect()->back();
            }
        }
        if ($user->save()) {
            session()->flash('success', '保存成功');
            return redirect()->route('users.index');
        } else {
            session()->flash('danger', '保存失败');
            return redirect()->back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = User::find($id);
        $user->delete();
        // 判断软删除是否成功
        if ($user->trashed()) {
            session()->flash('success', '删除成功');
        } else {
            session()->flash('danger', '删除失败');
        }
        return back();
    }

    /**
     * 修改用户角色界面
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editrole($id)
    {
        $user = User::find($id);
        $roles = Role::all();
        return view('admin.users.editrole', compact('roles', 'user'));
    }

    /**
     * 修改用户角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updaterole(Request $request, $id)
    {
        $this->validate($request, [
            'role' => 'required|array'
        ]);
        // 查找用户
        $user = User::find($id);
        // 删除用户原有所有角色
        $user->detachRoles();
        // 添加新角色到用户
        $user->attachRoles($request->role);

        session()->flash('success', '保存成功');
        return redirect()->route('users.index');
    }
}
